<?php
namespace app\admin\controller;
use think\facade\Db;
class Cate extends Adm
{
	use \app\admin\traits\Curd;
    public function index()
    {
    	return $this->fetch();
    }
    /**
     * [_add 扩展]
     * 
     */
    protected function _add()
    {
        $cates = ($this->_model)::select()->toArray();
        $cates = $this->arrtotreelist($cates,'parent_id');
        $this->assign(get_defined_vars());
    }
    //获取所有分类
    public function all()
    {
    	$data = ($this->_model)::select()->toArray();
    	$data = $this->arrtotreelist($data,'parent_id');
    	$count = null;
    	$this->assign(get_defined_vars());
    	$this->code = 0;
    	return $this->fetch();
    }
    private function listtotreearr(
        $lists,
        $parent_field='parent_id',
        $parent_id=0,
        $son_field='children'
    )
    {
        $list = [];
        $rows = $lists;
        foreach($rows as $k=>$v)
        {
            $data = $v;
            $data['children'] = [];
            if($v['parent_id']==$parent_id)
            {
                unset($lists[$k]);
                $sons = $this->arrtotreelist($lists,$parent_field,$v['id']);
                foreach($sons as $i=>$item){
                    array_push($data['children'], $item);
                }
                array_push($list, $data);
            }
        }
        return $list;
    }
    public function selectParent()
    {
        header('Content-Type:application/json; charset=utf-8');
        $data = Db::name('cate')->select();
        $data[] = [
            "id"=>"0",
            "name"=>"顶级分类",
            "parent_id"=>"-1",
            "sort"=>null
        ];
        $response = [
            'status'=>[
                'code'=>'200',
                'msessage'=>''
            ],
            'data'=>$data
        ];
        return json($response);
    }
    private function arrtotreelist($lists,$parent_field='parent_id',$parent_id=0)
    {
    	$list = [];
    	$rows = $lists;
    	foreach($rows as $k=>$v)
    	{
    		if($v['parent_id']==$parent_id)
    		{
    			array_push($list, $v);
    			unset($lists[$k]);
    			$sons = $this->arrtotreelist($lists,$parent_field,$v['id']);
    			foreach($sons as $i=>$item){
    				array_push($list, $item);
    			}
    		}
    	}
    	return $list;
    }
}
